<template>
  <el-dropdown size="mini" split-button trigger="click" @command="handleSetLanguage" class="language">
    <span>{{lang}}</span>
    <el-dropdown-menu slot="dropdown">
      <template v-for="(item, index) in langLs">
        <el-dropdown-item :command="index" :disabled="language===item.code" :key="item.code">{{item.name}}</el-dropdown-item>
      </template>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<style lang="scss">
  .language {
    .el-button {
      line-height: normal;
    }
  }
</style>

<script>
import { getSupportLang } from '@/api/login'
import { clearI18 } from '@/utils/i18n'
import { clearOptions } from '@/utils/getOptionis'
export default {
  name: 'newLangSelect',
  created() {
    getSupportLang().then(response => {
      const ls = response.data.data
      const first = ls[0]
      if (first) {
        this.langLs = first.options
      } else {
        this.langLs = [{ code: 'en_US', name: 'English' }, { code: 'zh_CN', name: '中文' }]
      }

      if (!this.$store.getters.language) {
        const lang = this.langLs[0].code
        this.lang = this.langLs[0].name
        this.$i18n.locale = lang
        this.$store.dispatch('setLanguage', lang)
      }
      this.langLs.forEach(lang => {
        if (lang.code === this.$store.getters.language) {
          this.lang = lang.name
          this.$store.dispatch('setLanguage', lang.code)
          return false
        }
      })
    })
  },
  data() {
    return {
      langLs: [],
      lang: ''
    }
  },
  computed: {
    language() {
      return this.$store.getters.language
    }
  },
  methods: {
    handleSetLanguage(index) {
      const item = this.langLs[index]
      this.lang = item.name
      this.$i18n.locale = item.code
      this.$store.dispatch('setLanguage', item.code)
      clearI18()
      clearOptions()
      this.$emit('lang-change')
    }
  }
}
</script>